package com.tangsm.spring.boot.async.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Executor;

/**
 * Async配置自定义线程池（建议首选）
 *
 * <p>实现AsyncConfigurer接口，并重写getAsyncExecutor()方法，指定默认线程池，优先级高于继承AsyncConfigurerSupport</p>
 *
 * @author tangsm
 */
@Component
@EnableAsync
public class AsyncConfigOne implements AsyncConfigurer {
    private static final Logger log = LoggerFactory.getLogger(AsyncConfigOne.class);

    @Resource(name = "defaultTaskExecutor")
    private ThreadPoolTaskExecutor defaultTaskExecutor;

    /**
     * 重写获取异步线程池任务执行器
     *
     * <pre>
     * 通过查看Spring源码关于@Async的默认调用规则，会优先查询源码中实现AsyncConfigurer这个接口的类，实现这个接口的类为AsyncConfigurerSupport。
     * 但默认配置的线程池和异步处理方法均为空，所以，无论是继承或者重新实现接口，都需指定一个线程池。且重新实现 public Executor getAsyncExecutor()方法。
     * </pew>
     *
     * @return 自定义异步线程池任务执行器
     */
    @Override
    public Executor getAsyncExecutor() {
        return defaultTaskExecutor;
    }

    /**
     * 重写获取异步未捕获异常处理程序，自定义打印信息
     *
     * @return 异步未捕获异常处理程序
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error("执行异步任务 [{}] 异常", method, ex);
    }
}
